package com.zerosoft.zerovideo.controller;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.zerosoft.zerovideo.service.VideoResourceService;
import io.netty.handler.codec.base64.Base64Decoder;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.json.JSONParser;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Set;

@RestController
public class VideoController {
    @jakarta.annotation.Resource
    private VideoResourceService service;
    /**
     * 根据文件路径获取视频流，输出格式为video/mp4
     * @param path 经过urlencode的文件路径
     * @param response
     * @return
     */
    @RequestMapping("/video/url/{fpath}")
    public ResponseEntity<Resource> getVideoUrl(@PathVariable("path") String path, HttpServletResponse response) {
        try
        {
//            String videoPath = URLDecoder.decode(path);
//            System.out.println(path);
//            Path fpath = Paths.get("/Users/guxuefeng/Downloads/反诈短剧-黑喵警长.mp4");
//            System.out.println(fpath.toUri());
            Resource resource = new UrlResource(Paths.get(URLDecoder.decode(path)).toUri());//(path.toUri());
            if (resource.exists() || resource.isReadable()) {
                HttpHeaders headers = new HttpHeaders();
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + resource.getFilename() + "\"");
                return ResponseEntity.ok().headers(headers).contentLength(resource.contentLength())
                        .contentType(MediaType.parseMediaType("video/mp4")).body(resource);

//                System.out.println("success");
//                // 设置响应的类型为视频流
//                response.setHeader("Accept-Ranges", "bytes");
//                response.setContentType("video/mp4");
//                // 设置响应的流式传输
//                response.setHeader("Content-Disposition", "inline; filename=video.mp4");
//
//                // 将文件的内容写入响应
//                org.springframework.util.FileCopyUtils.copy(resource.getInputStream(), response.getOutputStream());
            } else {
                // 文件未找到，可以返回404或其他错误处理
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return ResponseEntity.internalServerError().build();
            }
        }
        catch (Exception e)
        {
            System.out.println("error");
            System.out.println(e);
            // 处理文件读取过程中的异常
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
        return ResponseEntity.internalServerError().build();
    }

    @RequestMapping("/video/stream/{path}")
    public void streamVideo(@PathVariable("path") String path, HttpServletResponse response) throws IOException {
        String videoPath = URLDecoder.decode(path);
        System.out.println(videoPath);
        Resource resource = new FileSystemResource(Paths.get("/Users/guxuefeng/Downloads/", videoPath));
        System.out.println(resource.toString());
        response.setContentType(MediaType.parseMediaType("video/mp4").toString());
        response.setHeader("Content-Disposition", "inline; filename=\"video.mp4\"");

        try (InputStream inputStream = new FileInputStream(resource.getFile());
             OutputStream outputStream = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
        }
    }

    /**
     * 根据文件路径获取视频封面,用此作为视频的缩略图，输出为image/jpeg
     * @param path 经过urlencode的文件路径
     * @param response
     * @return
     */
    @RequestMapping("/video/cover/{path}")
    public ResponseEntity<byte[]> getVideoCover(@PathVariable("path") String path, HttpServletResponse response) {
        System.out.println(path);

        String param = new String(Base64.getDecoder().decode(path));
        System.out.println("params: " + param);
        Path filePath = Paths.get(param);
        System.out.println("filepath from params: " + filePath);
        filePath = Paths.get("/Users/guxuefeng/Downloads/反诈短剧-黑喵警长.mp4");
        System.out.println("filepath from direct: " + filePath);
        byte[] cover =service.getCover(filePath);
        System.out.println("cover: " + cover);
        try
        {
            Resource resource = new UrlResource(Paths.get(URLDecoder.decode(path)).toUri());//(path.toUri());
            if (resource.exists() || resource.isReadable()) {
                HttpHeaders headers = new HttpHeaders();
                headers.add(HttpHeaders.CONTENT_TYPE, "image/jpeg");

                BufferedImage image = ImageIO.read(Paths.get(URLDecoder.decode(path)).toFile());

                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                ImageIO.write(image, "jpeg", outputStream);
                byte[] imageBytes = outputStream.toByteArray();

                return ResponseEntity.ok().headers(headers).contentLength(resource.contentLength())
                        .contentType(MediaType.parseMediaType("video/mp4")).body(imageBytes);
            }
            else {
                // 文件未找到，可以返回404或其他错误处理
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return ResponseEntity.internalServerError().build();
            }
        }
        catch (Exception e){
            System.out.println("error");
            System.out.println(e);

            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return ResponseEntity.internalServerError().build();
        }

//        return ResponseEntity.internalServerError().build();
    }

    /**
     * 获取视频列表，输出为json，在service中根据文件内容，取固定数量的视频，这个数量在yml中配置
     * @return List<String>
     */
    @RequestMapping("/video/getvideos")
    public String getVideos()
    {
        Set res = service.getResources();
        JSONObject json = new JSONObject();
        json.put("code", 0);
        json.put("data", res);
        return json.toString();
    }
}
